/**
 * 
 */
package chances.wechat.applet;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import chances.wechat.utils.JSONUtils;




/**
 * @author chenxx
 *
 */
@Controller
public class AppletPhotoController {

	@Autowired
	private AppletPhotoService photoService;
	
	static Logger logger = LoggerFactory.getLogger("mprogramLogger");

	@RequestMapping(value = "/applet/uploadPhoto", method = RequestMethod.POST)
	public void uploadPhoto(HttpServletRequest request,HttpServletResponse response,
			@RequestParam(name="openId") String openId)
					throws Exception {
		AppletResponse result = new AppletResponse();
		List<MultipartFile> files = new ArrayList<MultipartFile>();
		
		try {
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			if (multipartResolver.isMultipart(request)) {
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				Iterator<String> iter = multiRequest.getFileNames();
				while (iter.hasNext()) {
					MultipartFile file = multiRequest.getFile(iter.next());
					if (file != null) {
						files.add(file);
					}

				}
			}
			result = photoService.savePhoto(files, openId);
			
		} catch (Exception e) {
			logger.error(e.toString(), e);
			e.printStackTrace();
		}
		response.getWriter().write(JSONUtils.fromObject(result));
	}

}
